 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
 </head>
 <body>
   <script>
    /**
    * Promise构造函数
    * excutor
    */
    const PENDING = 'pending'
    const FULFILLED = 'fulfilled'
    const REJECTED = 'rejected'
    class Promise{
      constructor(extcutor){
        this.state = PENDING
        this.value = undefined
        this.reason = undefined
        this.onFulfilled = []
        this.onRejected = []
        let resolve = (value)=>{
          console.log('resolve')
          if(this.state === PENDING){
            this.state = FULFILLED
            this.value = value
            this.onFulfilled.forEach(fn => fn.call(this,value))
          }
        }
        let reject = (err)=>{
          console.log('reject'+this.state)
          console.log(this.onRejected)
          if(this.state === PENDING){
            this.state = REJECTED
            this.reason = err
            this.onRejected.forEach(fn => fn.call(this,err))
          }
        }
        try{
          extcutor(resolve,reject)
        }catch(error){
          reject(error)
        }

      }

      then(onFulfilled,onRejected){
        // 判断是否函数
        console.log('then')
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (v)=>v
        onRejected = typeof onRejected === 'function' ? onRejected : (err)=>{throw err}
        return new Promise((resolve,reject)=>{
          this.onFulfilled.push((val)=>{
            try{
              let x = onFulfilled(val)
              x instanceof Promise ? x.then(resolve,reject) : resolve(x)
            }catch(err){
              reject(err)
            }
          })
          this.onRejected.push((val)=>{
            try{
              let x = onRejected(val)
              x instanceof Promise ? x.then(resolve,reject) : reject(x)
            }catch(err){
              reject(err)
            }
          })

        })
      }
    }

    var myP = new Promise(function(resolve, reject){
      console.log('执行')
      setTimeout(function(){
          reject(3)
      }, 1000)
    });

    myP.then(function(res){
        console.log(res)
    },function(err){
        console.log(err)
    });
    myP.then(function(res){
        console.log(2)
    },function(err){
        console.log(2)
    });
   </script>
 </body>
 </html>